import { initWebSocket, WebSocketMsg } from '@/utils/websocket';
import { DEV_WS_URL_HEAD, DEV_WS_URL_TAIL, PRO_WS_URL_HEAD, PRO_WS_URL_TAIL } from "@/api/websocket/websocketUrl";
import useQuoteStore from "@/store/modules/quote";
import { v4 as uuidv4 } from 'uuid';
const userStore = useQuoteStore();
let webSocket: any = null; // 初始化为null，避免在未初始化时访问
let isWebSocketOpen = false;
const initializeWebSocket = () => {
    webSocket = initWebSocket({
        url:
            (import.meta.env.VITE_WS_FLAG == "production" ? PRO_WS_URL_HEAD + PRO_WS_URL_TAIL : DEV_WS_URL_HEAD + DEV_WS_URL_TAIL) +
            "/r",
        open: () => {
            console.info("连接WebSocket成功");
            isWebSocketOpen = true;
        },
        message: (event: any) => {
            const webSocketMsg: WebSocketMsg = JSON.parse(event.data);
            //消息回写方法，根据type和topic确定消息类型，并执行相应的处理
            if (webSocketMsg.Type == "txtMessage" && webSocketMsg.Topic == "broker.quote.hq") {
                userStore.addQuote(webSocketMsg);
            }            
            // console.log('接收消息的回调', webSocketMsg);
        },
        close: () => {
            console.log("WebSocket连接已关闭");
            closeWebSocket();
        },
        error: () => {
            console.error("WebSocket发生错误");
            closeWebSocket();
        }
    });
};
//****************websocket推送********************
export const sendMessage = (topic: string, targetCodes: String[], message: any) => {
    console.log(message);
    if (message) {
        msgObj.value = {
            Type: 'txtMessage', // 假设服务端约定的订阅操作关键字
            Topic: topic,
            TargetCodes: targetCodes,
            RequestId: generateRequestId(),
            Data: message,
            // 其他字段...
        };
        if (webSocket) {
            webSocket.send(JSON.stringify(msgObj.value));
        }
        // message.value = '';
    }
};
export const openWebSocket = () => {
    if (!webSocket) {
        initializeWebSocket();
    }
};

export const closeWebSocket = () => {
    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
        webSocket.close();
    }
    webSocket = null;
    isWebSocketOpen = false;
};
const msgObj = ref<WebSocketMsg>();
let isSend = false;
// 新增：订阅topic的方法
export const subscribeTopic = (topic: string, targetCodes: String[]) => {
    if (isWebSocketOpen && topic) {
        msgObj.value = {
            Type: 'sub', // 假设服务端约定的订阅操作关键字
            Topic: topic,
            TargetCodes: targetCodes,
            RequestId: generateRequestId(),
        };
        webSocket.send(JSON.stringify(msgObj.value));
        isSend = true;
        // console.log(`已订阅Topic: ${topic}`);
    }
};

// 新增：取消订阅topic的方法
export const unsubscribeTopic = (topic: string, targetCodes: String[]) => {
    if (isWebSocketOpen && topic) {
        msgObj.value = {
            Type: 'unSub', // 假设服务端约定的订阅操作关键字
            Topic: topic,
            TargetCodes: targetCodes,
            RequestId: generateRequestId(),
        };
        webSocket.send(JSON.stringify(msgObj.value));
        isSend = true;
    }
};

//尝试重复订阅
export const retrySubscribe = async (topic: string, targetCodes: String[]) => {
    isSend = false;
    const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
    for (let i = 0; i < 3; i++) {
        if (!isSend) {
            // console.log('测试重新订阅次数：',i+1)
            subscribeTopic(topic, targetCodes);
            await delay(1000);
        }
    }
};

const generateRequestId = () => {
    return uuidv4();
};
